if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_PhieuXuatNhap_InsertHoaDonNhapHangNCC]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_PhieuXuatNhap_InsertHoaDonNhapHangNCC]
GO
CREATE PROC [sp_PhieuXuatNhap_InsertHoaDonNhapHangNCC](
	@Ki_hieu					nvarchar(50),
	@Ghi_chu					nvarchar(100),
	@Ma_khach_hang				nvarchar(10),
	@Ma_nhan_vien				int,
	@Tong_tien					float = 0,
	@Thue						float = 0,	
	@Tien_thue					float = 0,
	@Thanh_tien					float = 0,
	@Thanh_toan					float = 0,
	@Chiet_khau					float = 0,
	@Tien_chiet_khau			float = 0,
	@Ty_gia						float = 0,
	@Tien_no					float = 0,
	@Ma_hinh_thuc_thanh_toan	int,
	@Ma_ngoai_te				int,
	@ReturnID					int OUTPUT
)
AS
BEGIN
	DECLARE @Ngay_cap_nhat_cuoi datetime
	DECLARE @Loai_nhap_xuat		int

	SET @Ngay_cap_nhat_cuoi = getdate()
	SET @Loai_nhap_xuat = 1

	IF @Ma_khach_hang = null OR @Ma_khach_hang = ''
		SET @Ma_khach_hang = '0'
	SET @Ki_hieu = REPLACE(@Ki_hieu,'*','') + dbo.udf_GetKiHieuNhapXuat(@Loai_nhap_xuat)

	INSERT INTO PhieuNhapXuat(
						Ki_hieu,
						Ghi_chu,
						Ma_khach_hang,
						Ma_nhan_vien,
						Tong_tien,
						Thue,
						Tien_thue,
						Loai_nhap_xuat,
						Thanh_tien,
						Thanh_toan,
						Chiet_khau,
						Tien_chiet_khau,
						Ma_ngoai_te,
						Ty_gia,
						Tien_no,
						Ma_hinh_thuc_thanh_toan,
						Xuat_hoa_don,
						Ngay_cap_nhat_cuoi
	)
	VALUES(				
		@Ki_hieu,
		@Ghi_chu,
		@Ma_khach_hang,
		@Ma_nhan_vien,
		@Tong_tien,
		@Thue,
		@Tien_thue,
		@Loai_nhap_xuat,
		@Thanh_tien,
		@Thanh_toan,
		@Chiet_khau,
		@Tien_chiet_khau,
		@Ma_ngoai_te,
		@Ty_gia,
		@Tien_no,
		@Ma_hinh_thuc_thanh_toan,
		'0',
		@Ngay_cap_nhat_cuoi
	)
	SELECT @ReturnID = SCOPE_IDENTITY()
END
